 package com.oanda.blackberry.view;
 
 import com.oanda.blackberry.restapi.OrderListResponse;
 import com.oanda.blackberry.restapi.Quote;
 import com.oanda.blackberry.restapi.Symbol;
 import com.oanda.blackberry.util.AbstractController;
 import com.oanda.blackberry.util.DefaultController;
 import com.oanda.blackberry.util.Model;
 import com.oanda.blackberry.util.PropertyChangeEvent;
 import com.oanda.blackberry.util.StringUtils;
 import com.oanda.blackberry.util.log.Logger;
 import java.util.Enumeration;
 import java.util.Hashtable;
 import net.rim.device.api.system.Application;
 import net.rim.device.api.system.Bitmap;
 import net.rim.device.api.ui.Field;
 import net.rim.device.api.ui.Font;
 import net.rim.device.api.ui.Graphics;
 import net.rim.device.api.ui.UiApplication;
 import net.rim.device.api.ui.component.ListField;
 
 public class OrdersListField
 {
   private OrderListResponse[] listData;
   private ListField listField;
   private ListCallBack listFieldCallBack = null;
   private Quote[] quotes;
   private OrdersView callback;
 
   public OrdersListField(OrderListResponse[] ordersList)
   {
     this.listFieldCallBack = new ListCallBack();
 
     this.listField = new ListField() {
       protected void drawFocus(Graphics graphics, boolean on) {
       }
 
       protected int moveFocus(int amount, int status, int time) {
         int ret = super.moveFocus(amount, status, time);
         invalidate();
         return ret;
       }
 
       protected void moveFocus(int x, int y, int status, int time) {
         int oldSelection = getSelectedIndex();
         super.moveFocus(x, y, status, time);
         int newSelection = getSelectedIndex();
 
         if (oldSelection != -1) {
           invalidate(oldSelection);
         }
 
         if (newSelection != -1) {
           invalidate(newSelection);
         } else {
           setSelectedIndex(oldSelection);
           invalidate(oldSelection);
         }
       }
 
       protected void onDisplay() {
         super.onDisplay();
       }
 
       protected void onUndisplay() {
         super.onUndisplay();
       }
     };
     this.listField.setEmptyString("", 6);
     this.listData = ordersList;
     this.listField.setRowHeight(70);
 
     this.listField.setCallback(this.listFieldCallBack);
 
     int elementLength = ordersList.length;
     for (int count = 0; count < elementLength; count++)
       this.listField.insert(count);
   }
 
   public void setQuotes(Quote[] quotes)
   {
     this.quotes = quotes;
     if (this.listField != null)
       this.listField.invalidate();
   }
 
   public ListField getList() {
     return this.listField;
   }
 
   public OrderListResponse getOrderListSelected()
   {
     if (this.listData == null) return null;
     if (this.listField == null) return null;
 
     int index = this.listField.getSelectedIndex();
 
     if ((index > -1) && (index < this.listData.length)) {
       OrderListResponse data = this.listData[index];
       return data;
     }
     return null;
   }
 
   public OrderListResponse[] getOrderListResponses() {
     return this.listData;
   }
 
   void remove(long[] closed)
   {
     if (this.listData == null) return;
     if (this.listField == null) return;
     if (closed == null) return;
 
     final int selected = this.listField.getSelectedIndex();
 
     Hashtable v = new Hashtable();
     Hashtable h = new Hashtable();
     for (int i = 0; i < this.listData.length; i++) {
       if (this.listData[i] != null) {
         v.put(new Long(this.listData[i].getId()), this.listData[i]);
         h.put(new Long(this.listData[i].getId()), new Integer(i));
       }
     }
 
     for (int i = 0; i < closed.length; i++) {
       long l = closed[i];
       if ((v.containsKey(new Long(l))) && (v.get(new Long(l)) != null)) {
         v.remove(new Long(l));
       }
     }
 
     Enumeration e = v.elements();
     this.listData = new OrderListResponse[v.size()];
     int i = 0;
     while (e.hasMoreElements()) {
       this.listData[i] = ((OrderListResponse)e.nextElement());
       i++;
     }
 
     OrderListResponse.sort(this.listData);
 
     Runnable r = new Runnable() { private final int _selected=selected;
 
       public void run() { OrdersListField.this.listField.setCallback(OrdersListField.this.listFieldCallBack);
         OrdersListField.this.listField.setSize(OrdersListField.this.listData.length);
         if (OrdersListField.this.listData.length > this._selected)
           OrdersListField.this.listField.setSelectedIndex(this._selected);
         OrdersListField.this.listField.invalidate();
 
         if ((OrdersListField.this.listData == null) || ((OrdersListField.this.listData != null) && (OrdersListField.this.listData.length == 0)))
           StatusView2.showInfoDialog("No Open Orders.", new OKDialogListener()
           {
             public void performAction(Object o)
             {
               StatusView2.showYesNoDialog("Do you want to create a new order now?", new OKDialogListener()
               {
                 public void performAction(Object o) {
                   if (((Boolean)o).booleanValue())
                   {
                     if (OrdersListField.this.callback != null) {
                       OrdersListField.this.callback.controller.propertyChange(new PropertyChangeEvent(this, "newLimitOrderOpenBuy", null, null));
                     }
                   }
                   else if (OrdersListField.this.callback != null)
                     OrdersListField.this.callback.popScreen();
                 }
               });
             }
           }
           , false);
       }
     };
     UiApplication.getUiApplication().invokeLater(r);
   }
 
   void update(OrderListResponse[] trades)
   {
     Logger.log("update orl");
 
     if (this.listData == null) return;
     if (this.listField == null) return;
     if (trades == null) return;
 
     final int selected = this.listField.getSelectedIndex();
 
     Hashtable v = new Hashtable();
     for (int i = 0; i < this.listData.length; i++) {
       if (this.listData[i] != null)
         v.put(new Long(this.listData[i].getId()), this.listData[i]);
       else {
         Logger.log("listData[" + String.valueOf(i) + "] == null");
       }
     }
 
     for (int i = 0; i < trades.length; i++) {
       if (trades[i] == null) {
         continue;
       }
       long l = trades[i].getId();
       if (v.get(new Long(l)) != null)
       {
         v.put(new Long(l), trades[i]);
       }
       else
       {
         v.put(new Long(l), trades[i]);
       }
     }
 
     Enumeration e = v.elements();
     this.listData = new OrderListResponse[v.size()];
     int i = 0;
     while (e.hasMoreElements()) {
       this.listData[i] = ((OrderListResponse)e.nextElement());
       i++;
     }
 
     OrderListResponse.sort(this.listData);
 
     Runnable r = new Runnable() { private final int _selected=selected;
 
       public void run() { OrdersListField.this.listField.setCallback(OrdersListField.this.listFieldCallBack);
         OrdersListField.this.listField.setSize(OrdersListField.this.listData.length);
         if (OrdersListField.this.listData.length > this._selected)
           OrdersListField.this.listField.setSelectedIndex(this._selected);
         OrdersListField.this.listField.invalidate();
       }
     };
     UiApplication.getUiApplication().invokeLater(r);
   }
 
   private Quote getQuote(String symbol) {
     for (int i = 0; (this.quotes != null) && (i < this.quotes.length); i++) {
       if ((symbol != null) && (this.quotes[i] != null) && (symbol.equals(this.quotes[i].getSymbol()))) {
         return this.quotes[i];
       }
     }
     return null;
   }
 
   public void setCallback(OrdersView callback)
   {
     this.callback = callback;
   }
 
   private class ListCallBack extends AbstractListFieldCallBack
   {
     private Bitmap gained = Bitmap.getBitmapResource("pips-above-51x24.png");
     private Bitmap below = Bitmap.getBitmapResource("pips-below-51x24.png");
 
     public ListCallBack() {
       Bitmap bg = Bitmap.getBitmapResource("trades-row-480x70.png");
       Bitmap bgSelected = Bitmap.getBitmapResource("trades-row-selected-480x70.png");
 
       setBg(bg);
       setBgSelected(bgSelected);
     }
 
     public void drawListRow(ListField list, Graphics graphics, int index, int y, int w) {
       OrderListResponse currentRow = (OrderListResponse)get(list, index);
 
       if (currentRow == null) return;
 
       Logger.log("drawListRow");
       Quote currentRowQuote = OrdersListField.this.getQuote(currentRow.getSymbol());
 
       Bitmap icon = null;
       int height = list.getRowHeight();
       drawBackground(graphics, 0, y, w, height, OrdersListField.this.listField.getSelectedIndex() == index);
 
       int h = list.getRowHeight();
       int fontHeight = 24;
       Font font28Plain = DefaultController.getComponentFont().derive(0, fontHeight);
 
       graphics.setColor(16119285);
       graphics.setFont(font28Plain);
       graphics.drawText(currentRow.getSymbol(), 12, y + (h - 2 - fontHeight) / 2, 0x30 | 0x6);
 
       Symbol symbol = Model.getModel().getSymbol(currentRow.getSymbol());
       String profit = "updating...";
       double prof = 0.0D;
       int precious = -1;
       String ask;
       if ((symbol != null) && (currentRowQuote != null)) {
         precious = symbol.getPrecision();
 
         if (currentRow.getType().startsWith("B")) {
           prof = (currentRowQuote.getAsk() - currentRow.getPrice()) / symbol.getPiploc();
           profit = StringUtils.formatCurrency(StringUtils.columnRound(Math.abs(prof), 2));
         } else if (currentRow.getType().startsWith("S")) {
           prof = (currentRowQuote.getBid() - currentRow.getPrice()) / symbol.getPiploc();
           profit = StringUtils.formatCurrency(StringUtils.columnRound(Math.abs(prof), 2));
         }
 
         if (prof > 0.0D)
           icon = this.gained;
         else if (prof < 0.0D) {
           icon = this.below;
         }
 
         String bid = StringUtils.formatDouble(currentRowQuote.getBid(), precious);
         ask = StringUtils.formatDouble(currentRowQuote.getAsk(), precious);
       }
 
       if (profit != null) {
         int profitWidth = 125;
 
         if (profit.indexOf("updating") > -1) {
           graphics.setFont(font28Plain.derive(0, 20));
           graphics.drawText(profit, 135, y + (h - 2 - fontHeight) / 2, 0x30 | 0x4, profitWidth);
         } else {
           graphics.drawText(profit, 105, y + (h - 2 - fontHeight) / 2, 0x30 | 0x4, profitWidth);
         }
         graphics.setFont(font28Plain);
       }
 
       if (icon != null) {
         drawImage(graphics, 221, y, height, icon);
       }
 
       if (currentRow != null) {
         String dir = currentRow.getType().startsWith("S") ? "SHORT" : "LONG";
         dir = dir + " @ ";
         String at = Double.toString(currentRow.getPrice());
         String units = Integer.toString(currentRow.getUnits()) + " UNITS";
         int x = 270;
         int minWidth = 120;
 
         String tp = "";
         String sl = "";
         String ts = "";
         if (currentRow.getTakeProfit() > 0.0D) {
           tp = Double.toString(currentRow.getTakeProfit());
         }
         if (currentRow.getStopLoss() > 0.0D) {
           sl = Double.toString(currentRow.getStopLoss());
         }
         if (currentRow.getTrailingStop() > 0.0D) {
           double pips = symbol.getPips(currentRow.getTrailingStop());
           ts = Double.toString(pips);
         }
         Font limitsFont = DefaultController.getComponentFontTall(10);
 
         int k = 0;
         int i = limitsFont.getAdvance(ts);
         int j = limitsFont.getAdvance(tp);
         k = limitsFont.getAdvance(sl);
         int max = Math.max(i, j);
         max = Math.max(max, k);
 
         if ((60 < max) && (max < 70)) {
           minWidth += 30;
         }
         else if ((50 < max) && (max < 60)) {
           minWidth += 40;
         }
         else if ((40 < max) && (max < 50)) {
           minWidth += 55;
         }
         else if (max < 40) {
           minWidth += 80;
         }
 
         graphics.setFont(font28Plain.derive(0, 15));
         graphics.drawText(units, x, y + 6 * this.verticalPadding, 0x30 | 0x4, minWidth);
         graphics.setFont(font28Plain.derive(0, 15));
         graphics.drawText(dir, x, y + 2 * this.verticalPadding + (h - 15 - 8) / 2, 0x4 | 0x30, minWidth);
         graphics.setFont(font28Plain.derive(1, 15));
         graphics.drawText(at, x, y + 2 * this.verticalPadding + (h - 8 - this.plain22.getHeight()), 0x4 | 0x30, minWidth);
 
         x = 388;
         minWidth = 82;
 
         graphics.setFont(limitsFont);
 
         graphics.setColor(8956419);
         graphics.drawText(tp + " TP", x, y + 15, 0x30 | 0x5, minWidth);
         graphics.setColor(14287362);
         graphics.drawText(sl + " SL", x, y + 30, 0x30 | 0x5, minWidth);
         graphics.setColor(16762898);
         graphics.drawText(ts + " TS", x, y + 45, 0x30 | 0x5, minWidth);
       }
     }
 
     protected void drawBorder(Graphics graphics, int x, int y, int width, int height)
     {
       graphics.setColor(8421504);
       graphics.drawLine(x - 1, y, x + width - 1, y);
       graphics.drawLine(x - 1, y, x - 1, y + height - 1);
 
       graphics.drawLine(x + width, y - 1, x + width, y + height - 1);
       graphics.drawLine(x - 1, y + height - 1, x + width - 1, y + height - 1);
     }
 
     public Object get(ListField list, int index) {
       try {
         return OrdersListField.this.listData[index]; } catch (ArrayIndexOutOfBoundsException a) {
       }
       return null;
     }
   }
}

